// 企业级API服务层 - 模拟真实接口对接
import { Car } from '@/data/cars';

export interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
  timestamp: number;
}

export interface PaginationParams {
  page: number;
  pageSize: number;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

export interface CarSearchParams {
  keyword?: string;
  brand?: string;
  type?: 'new' | 'used';
  priceRange?: [number, number];
  fuelType?: string;
  yearRange?: [number, number];
  mileageRange?: [number, number];
  transmission?: string;
  color?: string;
  carLevel?: string;
}

// 模拟API延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

// 真实API调用 - 对接企业级后端接口
export class CarApiService {
  private static instance: CarApiService;
  private baseUrl = '/api';
  
  public static getInstance(): CarApiService {
    if (!CarApiService.instance) {
      CarApiService.instance = new CarApiService();
    }
    return CarApiService.instance;
  }

  // 搜索车辆 - 调用真实API
  async searchCars(params: CarSearchParams & PaginationParams): Promise<ApiResponse<{
    cars: Car[];
    total: number;
    page: number;
    pageSize: number;
    stats: {
      totalCars: number;
      newCars: number;
      usedCars: number;
      brandsCount: number;
      avgPrice: number;
    };
  }>> {
    // 构建查询参数
    const queryParams = new URLSearchParams();
    queryParams.append('page', params.page.toString());
    queryParams.append('pageSize', params.pageSize.toString());
    
    if (params.keyword) queryParams.append('keyword', params.keyword);
    if (params.brand) queryParams.append('brand', params.brand);
    if (params.type) queryParams.append('type', params.type);
    if (params.fuelType) queryParams.append('fuelType', params.fuelType);
    if (params.transmission) queryParams.append('transmission', params.transmission);
    if (params.color) queryParams.append('color', params.color);
    
    if (params.priceRange) {
      queryParams.append('priceMin', params.priceRange[0].toString());
      queryParams.append('priceMax', params.priceRange[1].toString());
    }
    
    if (params.yearRange) {
      queryParams.append('yearMin', params.yearRange[0].toString());
      queryParams.append('yearMax', params.yearRange[1].toString());
    }
    
    if (params.mileageRange) {
      queryParams.append('mileageMin', params.mileageRange[0].toString());
      queryParams.append('mileageMax', params.mileageRange[1].toString());
    }

    try {
      const response = await fetch(`${this.baseUrl}/cars?${queryParams}`);
      const data = await response.json();
      return data;
    } catch (error) {
      console.error('API调用失败:', error);
      throw error;
    }
  }

  // 获取品牌列表
  async getBrands(): Promise<ApiResponse<string[]>> {
    await delay(200);
    const { cars } = await import('@/data/cars');
    const brands = [...new Set(cars.map(car => car.brand))];
    
    return {
      code: 200,
      message: 'success',
      data: brands,
      timestamp: Date.now()
    };
  }

  // 获取车辆详情
  async getCarDetail(id: string): Promise<ApiResponse<any>> {
    await delay(150);
    const { cars } = await import('@/data/cars');
    const car = cars.find(c => c.id === id);
    
    if (!car) {
      return {
        code: 404,
        message: 'Car not found',
        data: null,
        timestamp: Date.now()
      };
    }
    
    return {
      code: 200,
      message: 'success',
      data: car,
      timestamp: Date.now()
    };
  }

  // 获取统计数据 - 调用真实API
  async getStats(): Promise<ApiResponse<{
    totalCars: number;
    newCars: number;
    usedCars: number;
    brandsCount: number;
    avgPrice: number;
  }>> {
    try {
      const response = await fetch(`${this.baseUrl}/stats`);
      const data = await response.json();
      return data;
    } catch (error) {
      console.error('获取统计数据失败:', error);
      throw error;
    }
  }
}

export const carApiService = CarApiService.getInstance();